package timerDemo;

import java.util.Comparator;
import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask> {

    private Runnable runnable;
    private long time;

    //初始化TimerTask任务
    public MyTimerTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = time;
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer {
    Object lock = new Object();
    //创建优先级队列，按时间顺序顺序执行
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    //创建线程，执行对队列中的任务
    public MyTimer() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (lock) {
                        while (queue.isEmpty()) {
                            lock.wait();
                        }
                            MyTimerTask task = queue.peek();
                            //获取当前时间的时间戳
                            long curTime = System.currentTimeMillis();
                            if (task.getTime() > curTime) {
                                lock.wait(task.getTime() - curTime);
                            } else {
                                task.run();
                                queue.poll();
                            }
                        }
                    } catch(InterruptedException e){
                        throw new RuntimeException(e);
                    }
                }
            });
            t.start();
        }

                //实现schedule方法,将任务放入队列当中
        public void schedule (Runnable runnable,long time){
            synchronized (lock) {
                queue.offer(new MyTimerTask(runnable, time));
                lock.notify();
            }
        }
    }

    public class Demo3 {
        public static void main(String[] args) {
            MyTimer myTimer = new MyTimer();
            myTimer.schedule(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello 2000");
                }
            }, 2000);
            System.out.println("hello main");
        }
    }
